package com.ponhu.ea2.goodsCenter.provider.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ponhu.ea2.entity.Inventory;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsCenterPushThirdpartyService;
import com.ponhu.ea2.goodsCenter.provider.service.InventoryService;
import com.ponhu.ea2.goodsCenter.provider.service.PhinventoryToAmqpService;
import com.ponhu.ea2.service.facade.InventoryApiService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author luyu
 * @create 2021-11-11 16:20
 */
@Slf4j
@Component
public class PushInventoryDataTask {

    @Resource
    GoodsCenterPushThirdpartyService goodsCenterPushThirdpartyService;

    @Resource
    InventoryApiService inventoryApiService;

    @Resource
    InventoryService inventoryService;

    @XxlJob("pushDataToWms")
    public void pushDataToWms() {
        goodsCenterPushThirdpartyService.pushWms();
    }

    @XxlJob("pushDataToStock")
    public void pushDataToStock() {
        goodsCenterPushThirdpartyService.pushStock();
    }

    @XxlJob("pushDataToPonhuAdd")
    public void pushDataToPonhuAdd() {
        goodsCenterPushThirdpartyService.pushPonhuAdd();
    }

    @XxlJob("pushDataToPonhuUpdate")
    public void pushDataToPonhuUpdate() {
        goodsCenterPushThirdpartyService.pushPonhuUpdate();
    }

    @XxlJob("pushDataToChuangjiCloud")
    public void pushDataToChuangjiCloud() {
        goodsCenterPushThirdpartyService.pushChuangjiCloud();
    }

    @XxlJob("pushDataToApplet")
    public void pushDataToApplet() {
        goodsCenterPushThirdpartyService.pushDataToApplet();
    }

    @XxlJob("pushPriceToPonhu")
    public void pushPriceToPonhu() {
        try {
            // 获取入参,文件的url
            long startTime = System.currentTimeMillis();
            String jobParam = XxlJobHelper.getJobParam();
            log.info("更新商品价格开始");
            Integer totalCount = 0;
            AtomicInteger successCount = new AtomicInteger();
            if (StringUtils.isNotBlank(jobParam)) {
                List<String> strings = readFileBytext(jobParam);
                log.info("更新商品价格入参为:{}", strings);
                List<Inventory> list = inventoryService.list(
                        new LambdaQueryWrapper<Inventory>().in(Inventory::getInventoryCode, strings));
                log.info("推送胖总管价格的商品为:{}", list);
                if (CollectionUtils.isNotEmpty(list)) {
                    totalCount = list.size();
                    list.stream().forEach(item -> {
                        if (inventoryApiService.syncThirdParties(item.getId(), null)) {
                            successCount.incrementAndGet();
                        }
                    });
                }
            }
            log.info("更新商品价格结束,总共有{}条,成功{}条,失败{}条,总共耗时{}毫秒",
                    totalCount, successCount,
                    (totalCount - successCount.intValue()),(System.currentTimeMillis()-startTime));
            // 设置任务结果
            XxlJobHelper.handleSuccess("更新商品价格结束,总共有" + totalCount + "条," +
                    "成功" + successCount + "条,失败"
                    + (totalCount.intValue() - successCount.intValue()) + "条,总共耗时"+
                    (System.currentTimeMillis()-startTime) + "毫秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @XxlJob("pushInventoryToThirdParty")
    public void pushInventoryToThirdParty() {
        log.info("定时任务-补推数据开始");
        long startTime = System.currentTimeMillis();
        String jobParam = XxlJobHelper.getJobParam();
        if(StringUtils.isNotBlank(jobParam)){
            JSONObject jsonObject = JSONObject.parseObject(jobParam);
            JSONArray pushMode = jsonObject.getJSONArray("pushMode");
            String url = jsonObject.getString("url");
            List<String> strings = readFileBytext(url);
            log.info("定时任务-补推数据,入参为:{}", strings);
            List<Inventory> list = inventoryService.list(
                    new LambdaQueryWrapper<Inventory>().in(Inventory::getInventoryCode, strings));
            Integer totalCount = list.size();
            String result = null;
            if (CollectionUtils.isNotEmpty(list)) {
                result = goodsCenterPushThirdpartyService.pushInventoryToThirdParty(pushMode, list);
            }
            log.info("{},补推任务总共耗时{}毫秒",result,(System.currentTimeMillis()-startTime));
            // 设置任务结果
            XxlJobHelper.handleSuccess(result +",总共有" + totalCount + "条," +
                     "总共耗时"+ (System.currentTimeMillis()-startTime) + "毫秒");
        }
    }

    private List<String> readFileBytext(String url) {
        List<String> strings = null;
        try {
            // 读取url的文件
            RestTemplate restTemplate = new RestTemplate(
                    new HttpComponentsClientHttpRequestFactory());
            org.springframework.core.io.Resource resource =
                    restTemplate.getForObject(url,
                            org.springframework.core.io.Resource.class);
            // 解析文件获取货品编码
            String s = "";
            InputStreamReader in = new InputStreamReader(
                    resource.getInputStream(),
                    "UTF-8");
            BufferedReader br = new BufferedReader(in);
            StringBuffer content = new StringBuffer();
            while ((s = br.readLine()) != null) {
                content = content.append(s);
            }
            strings = Arrays.asList(content.toString().split(","));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strings;
    }

}
